<template>
	<div ref="codeEditor" style="min-height: 300px; width: 80%"></div>
</template>

<script setup>
import { editor } from "monaco-editor";
import * as monaco from "monaco-editor";
import { language as javaLanguage } from "monaco-editor/esm/vs/basic-languages/java/java";
import { onMounted, ref, toRaw, defineProps, watch } from "vue";
// import { onBeforeRouteUpdate } from "vue-router";

const props = defineProps({
	codeValue: {
		type: String,
		default: ""
	},
	onCodeChange: {
		type: Function,
		default: () => {}
	}
});

const codeEditor = ref(null);

const standaloneEditorConstructionOptions = {
	theme: "vs", // 官方自带三种主题vs, hc-black, or vs-dark
	value: "", // 编辑器初始显示文字
	language: "java",
	folding: true, // 代码折叠
	autoIndent: true // 自动缩进
};

const initEditor = () => {
	// 初始化编辑器，确保dom已经渲染
	editor.value = monaco.editor.create(codeEditor.value, standaloneEditorConstructionOptions);

	// 设置初始值
	editor.value.setValue(standaloneEditorConstructionOptions.value);

	editor.value.onDidChangeModelContent(() => {
		// console.log(toRaw(editor.value).getValue());
		props.onCodeChange(toRaw(editor.value).getValue());
	});

	// 设置光标位置
	setPositionToEnd();
};

const setPositionToEnd = () => {
	const model = editor.value.getModel();
	const lastLineNumber = model.getLineCount();
	const lastLineLength = model.getLineContent(lastLineNumber).length;

	const position = {
		lineNumber: lastLineNumber,
		column: lastLineLength + 1
	};

	editor.value.setPosition(position);
	editor.value.revealPositionInCenterIfOutsideViewport(position);
};

onMounted(() => {
	initEditor();

	if (standaloneEditorConstructionOptions.language === "java") {
		monaco.languages.registerCompletionItemProvider("java", {
			provideCompletionItems: () => {
				let suggestions = [];
				javaLanguage.keywords.forEach(keyword => {
					suggestions.push({
						label: keyword,
						kind: monaco.languages.CompletionItemKind.Keyword,
						insertText: keyword
					});
				});
				return {
					suggestions: suggestions
				};
			}
		});
	}
});

watch(
	() => props.codeValue,
	val => {
		if (val) {
			editor.value.setValue(val);
			setPositionToEnd(); // 更新光标位置
		} else {
			editor.value.setValue("");
			setPositionToEnd();
		}
	}
	// {
	//   immediate: true,
	// }
);
</script>
